package com.auto.autoapp.util

import android.graphics.Rect
import android.view.accessibility.AccessibilityNodeInfo
import com.ven.assists.AssistsCore
import com.ven.assists.AssistsCore.click

fun String.getNodeList(): Result<List<AccessibilityNodeInfo>> {
    val node = AssistsCore.findById(this).filter {
        it.isVisibleToUser
    }
    return Result.success(node)
}

fun String.getNodeById(last: Boolean = true): Result<AccessibilityNodeInfo> {
    val nodeList = getNodeList()
    val node = if (last) nodeList.getOrNull()?.lastOrNull() else nodeList.getOrNull()?.firstOrNull()
    if (node == null) {
        return success.nodeCodeException()
    }
    return Result.success(node)
}

suspend fun AccessibilityNodeInfo.clickOrTap(): Result<Int> {
    var clickResult = this.click()
    if (!clickResult) {
        val rect = Rect()
        this.getBoundsInScreen(rect)
        clickResult =
            AssistsCore.gestureClick(rect.centerX().toFloat(), rect.centerY().toFloat(), 100)
    }
    if (clickResult) {
        return Result.success(success)
    }
    return clickFail.opException()
}

suspend fun String.clickOrTap(): Result<Int> {
    val nodeResult = getNodeById()
    if (nodeResult.isFailure) {
        return nodeNotFind.opException()
    }
    val node = nodeResult.getOrThrow()
    var clickResult = node.click()
    if (!clickResult) {
        val rect = Rect()
        node.getBoundsInScreen(rect)
        clickResult =
            AssistsCore.gestureClick(rect.centerX().toFloat(), rect.centerY().toFloat(), 100)
    }
    if (clickResult) {
        return Result.success(success)
    }
    return clickFail.opException()

}